﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharedLib.MessageFramework;
using SharedLib.MessageFramework.Messages;
using System.Xml;
using System.Net;
using SharedLib.Helpers;
using Tracy.Messages;
using SharedLib.MessageFramework.Handlers;

namespace Tracy.Handlers
{
    public class GetXmlFromURLHandler : TaskMessageHandler
    {
        protected override void ProcessMessage(TaskMessage msg)
        {
            if (msg is GetXmlFromURLMessage)
            {
                ProcessMessage((GetXmlFromURLMessage)msg);
            }
        }
        private void ProcessMessage(GetXmlFromURLMessage msg)
        {
            try
            {
                string url = msg.GenericData;
                //Console.WriteLine("Begin retrieving url " + url);
                WebClient client = new WebClient();
                byte[] contentData = client.DownloadData(url);
                string content = StringHelper.SanitizeXmlString(Encoding.UTF8.GetString(contentData));
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(content);
                msg.Result = doc;
                //Console.WriteLine("End retrieving url " + url);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException(String.Format("Error retrieving xml from URL {0} : {1}", msg.GenericData, ex.Message), ex);
            }
        }
    }
}
